package myServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;




















import util.IPUtils;
import util.TimeUtils;
import util.UUIDUtils;
import bean.MenuBean;
import bean.UserBean;


import databaseDAO.LoginDao;
import databaseDAO.Menu2Dao;
import databaseDAO.UserManagement;


/**
 * 
 * @author maxinehehe
 * 登录
 * 主要操作与用户相关操作
 */
public class LoginServlet extends HttpServlet{
	
	public void doPost(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		doGet(request,response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException,IOException{
		String loginstate = request.getParameter("a");  // 拿到登录状态
		
		try{
				if(loginstate.equals("login")){
					// 如果是login 则允许登录		
					
						this.userLogin(request, response);
					
				}else if(loginstate.equals("loginOut")){
					//System.out.println("退出");
					this.loginOut(request, response);
				}else if(loginstate.equals("deleteUser")){
					// 注销
					//System.out.println("删除用户");
					this.deleteUser(request, response);
				}else if(loginstate.equals("managerUser")){
					// 管理用户，管理员权限
					this.managerUser(request, response);
					
				}else if(loginstate.equals("modifyUser")){
					// 修改用户
					this.updateUserByID(request, response);
				}else if(loginstate.equals("adduser")){
					this.addUser(request, response);
				}else if(loginstate.equals("goToUpdate")){
					this.goToUpdate(request,response);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	private void goToUpdate(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UserBean ub = new UserBean();
		String userID = request.getParameter("uid");
		
		String nickName = request.getParameter("nickName");
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String roleID = request.getParameter("userRole");
		//System.out.println("userRoleID-or:"+userRole);
		String userCreateTime = request.getParameter("userCreateTime");
		String loginTime = request.getParameter("loginTime");
		String loginTimeLong = request.getParameter("loginTimeLong");
		String currentStatus = request.getParameter("currentStatus");
		String IP = request.getParameter("IP");
		String userDescription = request.getParameter("userDescription");
		System.out.println("userName:"+userName);
		ub.setUserID(userID);
		ub.setNickName(nickName);
		ub.setUserName(userName);
		ub.setPassword(password);
		ub.setRoleID(roleID);
		ub.setUserCreateTime(userCreateTime);
		ub.setLoginTime(loginTimeLong);
		ub.setLoginTimeLong(loginTimeLong);
		ub.setCurrentStatus(currentStatus);
		ub.setIP(IP);
		ub.setUserDescription(userDescription);
		
		UserManagement um = new UserManagement();
		um.updateUser(ub);
		
		this.managerUser(request, response);  // 管理用户
		
	}

	public void destroy(){
	}
	
	public void doError(HttpServletRequest request, HttpServletResponse response,String error)
			throws ServletException,IOException{ // 错误处理
		request.setAttribute("error", error);  // 设置属性
		// 然后转发
//		System.out.println("ERROR");
		request.getRequestDispatcher("/error.jsp").forward(request, response);  // 未定义
		// 转发至products页面
	}
	
	// 编写添加用户
	public void addUser(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		UserBean ub = new UserBean();
		String nickName = request.getParameter("nickName");
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String userDescription = request.getParameter("userDescription");
		String roleID = request.getParameter("userRole");  // ID
		//String[] rolID = request.getParameterValues(roleName);
		System.out.println("roleID:"+roleID);
		UserManagement um = new UserManagement();
		ub.setUserID(UUIDUtils.getId()); // 设置ID
		ub.setNickName(nickName);
		ub.setUserName(userName);
		ub.setPassword(password);
		ub.setUserDescription(userDescription);
		
		ub.setRoleID(roleID);  //
		
		ub.setUserCreateTime(TimeUtils.getCurrTime());
		ub.setLoginTime(TimeUtils.getCurrTime());
		ub.setLoginTimeLong("0");
		ub.setCurrentStatus("离线");
		ub.setIP("0");   // 新增加时IP默认为空
		
		int re = 0;
		try {
			re = um.adduser(ub);  // add database
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		//System.out.println("re:"+re+"-"+nickName);
		PrintWriter out = response.getWriter();
		out.println("<script charset='utf-8' type='text/javascript'>alert('ok！');window.history.back(-1);</script>");
	    //request.getRequestDispatcher("/regist_succ.jsp").forward(request, response);
	    
	    
	}
	
	
	

	public void userLogin(HttpServletRequest request,HttpServletResponse response)
			throws Exception{
		
		HttpSession session = request.getSession(false);
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		
		LoginDao ld = new LoginDao();
		UserBean ub = ld.login(username, password);  // 拿到登录信息
		// 对登录信息进行判断
		if(ub==null){
			
			String islogin = "false";
			
			session.setAttribute("islogin", islogin);
//			Response.Write("<script>alert('您的购物车还空空如也，赶快去添加吧！');location.href='ShowFoods.aspx';</script>");
			PrintWriter out = response.getWriter();
			out.println("<script charset='utf-8' type='text/javascript'>alert('username or password is wrong！');window.history.back(-1);</script>");
			//out.println("<script charset='utf-8'>alert('用户名或密码错误！');</script>");
			//request.getRequestDispatcher("/index.jsp").forward(request, response);

			
		}else{
			    ub.setIP(IPUtils.getIpAddr(request));
			    ld.updateUserDao(ub);  // 更新用户
			    
				session.setAttribute("user", ub); // setAttribute
				
				// 查询用户权限
				MenuBean mbUser = new Menu2Dao().queryRoleByRoleIDInMenu2(ub.getRoleID());
				//System.out.println("mbuser"+mbUser.getMenuID());
				session.setAttribute("mbUser", mbUser); // setAttribute
				
				List<String> lsMenuID = new Menu2Dao().getMenuIDByroleID(ub.getRoleID());
				session.setAttribute("lsMenuID", lsMenuID); // setAttribute
				//request.getRequestDispatcher("/welcome/limitationManagement.jsp").forward(request, response);
				response.sendRedirect("welcome/limitationManagement.jsp");	
			
		}
	}
	
	
	public void loginOut(HttpServletRequest request, HttpServletResponse response)
		throws ServletException,IOException, Exception{
		HttpSession session = request.getSession(false); // 不进行新的创建 若存在会话则返回该会话，否则返回NULL
		// 修改用户登录时长
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		UserBean ub =  (UserBean) session.getAttribute("user");
		new LoginDao().updateUserDao2LoginOut(ub);  // 更新
		// 清空
		session.invalidate();
		// 转发 至首页
		//System.out.println("路径："+basePath);
		response.sendRedirect(basePath+"index.jsp");
		//request.getRequestDispatcher(basePath+"index.jsp").forward(request, response);
	}
	
	
	public void managerUser(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		
		UserManagement um = new UserManagement();
		List<UserBean> listUb = um.queryAllUsers();
		//System.out.println("长度"+listUb.size());
		//查询IP
		//System.out.println(IPUtils.getIpAddr2(request));
		
		
		
		HttpSession session = request.getSession(false);
		session.setAttribute("listUb", listUb);
		response.sendRedirect(basePath+"admin/managerUsers.jsp");
	}
	
	
	public void deleteUser(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String uid = request.getParameter("uid");
		UserManagement um = new UserManagement();
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		
		
		um.delUserByUid(uid);
	    List<UserBean> listUb = um.queryAllUsers();
	    HttpSession session = request.getSession(false);
		session.setAttribute("listUb", listUb);
		response.sendRedirect(basePath+"admin/managerUsers.jsp");
		
		
		
	}
	
	public void updateUserByID(HttpServletRequest request,HttpServletResponse response) throws ClassNotFoundException, ServletException, IOException{
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		 HttpSession session = request.getSession(false);
		
		String uid = request.getParameter("uid");
		UserManagement um = new UserManagement();
		UserBean userByModify = um.queryByUid(uid);
		session.setAttribute("userByModify", userByModify);
		// 转
		response.sendRedirect(basePath+"admin/update_user_admin.jsp");
	}
	
	
}
